<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发现单位" prop="discoveryUnit">
        <el-select v-model="queryParams.discoveryUnit" placeholder="请选择发现单位" clearable>
          <el-option
              v-for="dict in dict.type.sys_user_company"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="信息单号" prop="oddNumber">
        <el-input
            v-model="queryParams.oddNumber"
            placeholder="请输入信息单号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="orderUnit">
        <el-input
            v-model="queryParams.orderUnit"
            placeholder="请输入单位"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="deptAbbreviation">
        <el-select v-model="queryParams.deptAbbreviation" placeholder="请选择部门" clearable>
          <el-option
              v-for="dict in dict.type.dept_abbreviation"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目号" prop="projectNumber">
        <el-input
            v-model="queryParams.projectNumber"
            placeholder="请输入项目号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="零件名称" prop="partName">
        <el-input
            v-model="queryParams.partName"
            placeholder="请输入零件名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结论" prop="handlingConclusion">
        <el-select v-model="queryParams.handlingConclusion" placeholder="请选择结论" clearable>
          <el-option
              v-for="dict in dict.type.inform_conclusion"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="严重级别" prop="severityLevel">
        <el-input
            v-model="queryParams.severityLevel"
            placeholder="请输入严重级别"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登记时间">
        <el-date-picker
            v-model="daterangeRegistrationTime"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['quality:rejectsnLosses:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['quality:rejectsnLosses:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['quality:rejectsnLosses:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['quality:rejectsnLosses:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleAllExport"
            v-hasPermi="['quality:rejectsnLosses:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportBlank"
            v-hasPermi="['quality:rejectsnLosses:export']"
        >毛坯</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportPart"
            v-hasPermi="['quality:rejectsnLosses:export']"
        >零件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExportMov"
            v-hasPermi="['quality:rejectsnLosses:export']"
        >手动</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rejectsnLossesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="rejectsnId" v-if="true" width="60"/>
      <el-table-column label="发现单位" align="center" prop="discoveryUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_company" :value="scope.row.discoveryUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="信息单号" align="center" prop="oddNumber" width="130"/>
      <el-table-column label="单位" align="center" prop="orderUnit" />
      <el-table-column label="部门" align="center" prop="deptAbbreviation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dept_abbreviation" :value="scope.row.deptAbbreviation"/>
        </template>
      </el-table-column>
      <el-table-column label="项目号" align="center" prop="projectNumber" />
      <el-table-column label="零件名称" align="center" prop="partName" />
      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column label="工时" align="center" prop="workingHours" />
<!--      <el-table-column label="单价" align="center" prop="unitPrice" />-->
<!--      <el-table-column label="损失" align="center" prop="lossAmount" />-->
      <el-table-column label="严重级别" align="center" prop="severityLevel" width="72"/>
      <el-table-column label="结论" align="center" prop="handlingConclusion" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inform_conclusion" :value="scope.row.handlingConclusion"/>
        </template>
      </el-table-column>
      <el-table-column label="登记时间" align="center" prop="registrationTime" sortable width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registrationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click.stop="handleUpdate(scope.row)"
              v-hasPermi="['quality:rejectsnLosses:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click.stop="handleDelete(scope.row)"
              v-hasPermi="['quality:rejectsnLosses:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改不合格品损失对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发现单位" prop="discoveryUnit">
          <el-select v-model="form.discoveryUnit" placeholder="请选择发现单位">
            <el-option
                v-for="dict in dict.type.sys_user_company"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="责任单位" prop="responsibilityUnit">
          <el-select v-model="form.responsibilityUnit" placeholder="请选择责任单位">
            <el-option
                v-for="dict in dict.type.sys_user_company"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="信息单号" prop="oddNumber">
          <el-input v-model="form.oddNumber" placeholder="请输入信息单号" />
        </el-form-item>
        <el-form-item label="单位" prop="orderUnit">
          <el-input v-model="form.orderUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="部门" prop="deptAbbreviation">
          <el-select v-model="form.deptAbbreviation" placeholder="请选择部门">
            <el-option
                v-for="dict in dict.type.dept_abbreviation"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入产品编号" />
        </el-form-item>
        <el-form-item label="零件件号" prop="partNumber">
          <el-input v-model="form.partNumber" placeholder="请输入零件件号" />
        </el-form-item>
        <el-form-item label="项目号" prop="projectNumber">
          <el-input v-model="form.projectNumber" placeholder="请输入项目号" />
        </el-form-item>
        <el-form-item label="零件名称" prop="partName">
          <el-input v-model="form.partName" placeholder="请输入零件名称" />
        </el-form-item>
        <el-form-item label="材质" prop="material">
          <el-input v-model="form.material" placeholder="请输入材质" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="工时" prop="workingHours">
          <el-input v-model="form.workingHours" placeholder="请输入工时" />
        </el-form-item>
        <!--        <el-form-item label="单价" prop="unitPrice">-->
        <!--          <el-input v-model="form.unitPrice" placeholder="请输入单价" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="损失" prop="lossAmount">-->
        <!--          <el-input v-model="form.lossAmount" placeholder="请输入损失" />-->
        <!--        </el-form-item>-->
        <el-form-item label="数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="不合格信息" prop="inspectionStatus">
          <el-input v-model="form.inspectionStatus" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="处理建议" prop="handlingSuggestion">
          <el-input v-model="form.handlingSuggestion" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="原因代码" prop="reasonCode">
          <el-input v-model="form.reasonCode" placeholder="请输入原因代码" />
        </el-form-item>
        <el-form-item label="缺陷代码" prop="defectCode">
          <el-input v-model="form.defectCode" placeholder="请输入缺陷代码" />
        </el-form-item>
        <el-form-item label="处理结论" prop="handlingConclusion">
          <el-select v-model="form.handlingConclusion" placeholder="请选择处理结论">
            <el-option
                v-for="dict in dict.type.inform_conclusion"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登记时间" prop="registrationTime">
          <el-date-picker clearable
                          v-model="form.registrationTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择登记时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body style="text-align: center">
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRejectsnLosses, getRejectsnLosses, delRejectsnLosses, addRejectsnLosses, updateRejectsnLosses } from "@/api/quality/rejectsnLosses";
import { required } from '@/utils/rules'
import { getToken } from '@/utils/auth'

export default {
  name: "RejectsnLosses",
  dicts: ['sys_user_company', 'dept_abbreviation','inform_conclusion'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 不合格品损失表格数据
      rejectsnLossesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 登记时间时间范围
      daterangeRegistrationTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        discoveryUnit: undefined,
        responsibilityUnit: undefined,
        oddNumber: undefined,
        orderUnit: undefined,
        deptAbbreviation: undefined,
        contractNumber: undefined,
        partNumber: undefined,
        projectNumber: undefined,
        partName: undefined,
        material: undefined,
        weight: undefined,
        workingHours: undefined,
        unitPrice: undefined,
        lossAmount: undefined,
        severityLevel: undefined,
        number: undefined,
        inspectionStatus: undefined,
        handlingSuggestion: undefined,
        reasonCode: undefined,
        defectCode: undefined,
        handlingConclusion: undefined,
        registrationTime: undefined,
      },
      // 不合格品导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/quality/rejectsnLosses/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rejectsnId: [required],
        discoveryUnit: [required],
        responsibilityUnit: [required],
        oddNumber:[required],
        orderUnit: [required],
        deptAbbreviation: [required],
        contractNumber:[required],
        partNumber: [required],
        projectNumber: [required],
        partName: [required],
        material: [required],
        weight: [required],
        workingHours:[required],
        unitPrice:[required],
        lossAmount: [required],
        severityLevel:[required],
        number: [required],
        inspectionStatus:[required],
        handlingSuggestion:[required],
        reasonCode: [required],
        defectCode: [required],
        handlingConclusion: [required],
        registrationTime: [required],
      }
    };
  },
  created() {
    this.getList();
  },
  computed: {
    formatNumber() {
      return function (value) {
        // 对数值进行精度处理
        return Number(value).toFixed(1); // 保留两位小数
      }
    }
  },
  methods: {

    /** 查询不合格品损失列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeRegistrationTime && '' != this.daterangeRegistrationTime) {
        this.queryParams.params["beginRegistrationTime"] = this.daterangeRegistrationTime[0];
        this.queryParams.params["endRegistrationTime"] = this.daterangeRegistrationTime[1];
      }
      listRejectsnLosses(this.queryParams).then(response => {
        this.rejectsnLossesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        rejectsnId: undefined,
        discoveryUnit: undefined,
        responsibilityUnit: undefined,
        oddNumber: undefined,
        orderUnit: undefined,
        deptAbbreviation: undefined,
        contractNumber: undefined,
        partNumber: undefined,
        projectNumber: undefined,
        partName: undefined,
        material: undefined,
        weight: undefined,
        workingHours: undefined,
        unitPrice: undefined,
        lossAmount: undefined,
        severityLevel: undefined,
        number: undefined,
        inspectionStatus: undefined,
        handlingSuggestion: undefined,
        reasonCode: undefined,
        defectCode: undefined,
        handlingConclusion: undefined,
        registrationTime: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRegistrationTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.rejectsnId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加不合格品损失";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const rejectsnId = row.rejectsnId || this.ids
      getRejectsnLosses(rejectsnId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改不合格品损失";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.rejectsnId != null) {
            updateRejectsnLosses(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRejectsnLosses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rejectsnIds = row.rejectsnId || this.ids;
      this.$modal.confirm('是否确认删除不合格品损失编号为"' + rejectsnIds + '"的数据项？').then(() => {
        this.loading = true;
        return delRejectsnLosses(rejectsnIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 全部导出按钮操作 */
    handleAllExport() {
      this.download('quality/rejectsnLosses/exportAll', {
        ...this.queryParams
      }, `rejectsnLosses_${new Date().getTime()}.xlsx`)
    },
    /** 选择项导出按钮操作 */
    handleExport(row) {
      const rejectsnIds = row.rejectsnId || this.ids;
      this.download('quality/rejectsnLosses/exportSelect/'+rejectsnIds, {
        ...this.queryParams
      }, `rejectsnLosses_${new Date().getTime()}.xlsx`)
    },
    /** 选择项导出毛坯项目号按钮操作 */
    handleExportBlank(row) {
      const rejectsnIds = row.rejectsnId || this.ids;
      this.download('quality/rejectsnLosses/exportSelectBlank', {
        ...this.queryParams
      }, `rejectsnBlank_${new Date().getTime()}.xlsx`)
    },
    /** 选择项导出零件项目号按钮操作 */
    handleExportPart(row) {
      const rejectsnIds = row.rejectsnId || this.ids;
      this.download('quality/rejectsnLosses/exportSelectPart', {
        ...this.queryParams
      }, `rejectsnPart_${new Date().getTime()}.xlsx`)
    },
    /** 选择项导出零件项目号按钮操作 */
    handleExportMov(row) {
      const rejectsnIds = row.rejectsnId || this.ids;
      this.download('quality/rejectsnLosses/exportSelectMov', {
        ...this.queryParams
      }, `rejectsnMov_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('quality/rejectsnLosses/importTemplate', {
      }, `rejectsnLosses_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
